#include <string.h>
#include "esp_log.h"
#include "color_light.h"
#include "uart_protocol.h"

static const char *TAG = "uart_protocol";

uint8_t flag_rx_frame_finish = 0;

uint8_t uart_frame_get_state(void)
{
    return(flag_rx_frame_finish);
}
uint8_t uart_frame_set_state(uint8_t state)
{
    flag_rx_frame_finish = state;
    return(1);
}
void array_clear(uint8_t *pbuf,uint16_t length)
{
    uint16_t i = 0;
    for(i=0;i<length;i++){
        pbuf[i] = 0;
    }
}
uint8_t uart_protocol_decoding(uint8_t *pbuf,uint16_t length)
{
    uint8_t  state = 0;
    uint16_t i = 0;
    static uint16_t led_num = 0;
    static uint8_t step = 0;
    static uint8_t frame_data[1024] = {0};
    static uint16_t data_len = 0;
    static uint16_t frame_count = 0;

    switch(step)
    {
        case 0://数据头
          if(pbuf[0]=='A'&&pbuf[1]=='d'&&pbuf[2]=='a'){
              led_num = pbuf[4]+1;
              led_strip_set_num(led_num);
              memcpy(frame_data,pbuf,length);
              if(length < (led_num*3+DATA_OFFSET)){
                  data_len += length;
                  step = 1;
              }else{ 
                  state = 1;
              }
          }
          break;
        case 1://RGB数据
          memcpy(&frame_data[data_len],pbuf,length);
          data_len += length;
          if(data_len >= (led_num*3+DATA_OFFSET)){
              state = 1;
          }
          break;
        case 2:
           break;
    }
    if(state == 1){
       for(i=0;i<led_num;i++){
            led_strip_set_color(i,frame_data[DATA_OFFSET+3*i],frame_data[DATA_OFFSET+3*i+1],frame_data[DATA_OFFSET+3*i+2]);
       }
       //ESP_LOGI(TAG,"\r\nframe rx success!!!");
       ESP_LOGI(TAG,"\r\ndata_len = %d",data_len);
       ESP_LOGI(TAG,"\r\nframe_count: %d",frame_count);
       //ESP_LOG_BUFFER_HEXDUMP(TAG,frame_data,data_len,ESP_LOG_INFO);
       array_clear(frame_data,data_len);
       step = 0;
       data_len = 0;
       flag_rx_frame_finish = 1;
       frame_count++;
    }
    return state;
}



